import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { nameAnalysis, getNameAnalysisDetail } from '../../services/tools';
import { createOrder, payOrder } from '../../services/payment';
import useAuthStore from '../../store/auth';
import usePaymentStore from '../../store/payment';

const NameAnalysis: React.FC = () => {
  const [name, setName] = useState('');
  const [gender, setGender] = useState<number>(1); // 默认男性
  const [analysisData, setAnalysisData] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [showPayment, setShowPayment] = useState(false);
  const [paymentLoading, setPaymentLoading] = useState(false);
  
  const navigate = useNavigate();
  const isAuthenticated = useAuthStore(state => state.isAuthenticated);
  const updateBalance = usePaymentStore(state => state.updateBalance);
  const setPendingOrder = usePaymentStore(state => state.setPendingOrder);
  
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 表单验证
    if (!name) {
      setError('请输入姓名');
      return;
    }
    
    try {
      setLoading(true);
      setError('');
      
      // 调用姓名测算API
      const response = await nameAnalysis({ name, gender });
      
      if (response.code === 200) {
        setAnalysisData(response.data);
        setShowPayment(!response.data.isPaid);
      } else if (response.code === 403) {
        // 需要付费
        setAnalysisData(response.data);
        setShowPayment(true);
      } else {
        setError(response.message || '姓名测算失败');
      }
    } catch (err: any) {
      setError(err.message || '姓名测算失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  const handlePayment = async () => {
    if (!isAuthenticated) {
      // 未登录，跳转到登录页
      navigate('/login');
      return;
    }
    
    try {
      setPaymentLoading(true);
      
      // 创建订单
      const orderResponse = await createOrder({
        productType: 'name_analysis_detail',
        productId: analysisData.analysisId,
        amount: isAuthenticated ? 0.1 : 1.1
      });
      
      if (orderResponse.code !== 200) {
        throw new Error(orderResponse.message || '创建订单失败');
      }
      
      // 支付订单
      const payResponse = await payOrder({
        orderNo: orderResponse.data.orderNo,
        paymentType: 'wallet'
      });
      
      if (payResponse.code === 200) {
        // 支付成功，更新钱包余额
        updateBalance(payResponse.data.balance);
        
        // 重新获取详情
        const detailResponse = await getNameAnalysisDetail(analysisData.analysisId);
        if (detailResponse.code === 200) {
          setAnalysisData(detailResponse.data);
          setShowPayment(false);
        }
      } else {
        throw new Error(payResponse.message || '支付失败');
      }
    } catch (err: any) {
      setError(err.message || '支付失败，请稍后再试');
      
      // 如果是余额不足，跳转到钱包充值页面
      if (err.message.includes('余额不足')) {
        setPendingOrder({
          orderNo: null,
          amount: isAuthenticated ? 0.1 : 1.1,
          productType: 'name_analysis_detail',
          productId: analysisData.analysisId
        });
        navigate('/wallet');
      }
    } finally {
      setPaymentLoading(false);
    }
  };
  
  // 模拟基础分析数据
  const mockBasicAnalysis = {
    name: name,
    gender: gender === 1 ? '男' : '女',
    strokes: '15',
    fiveElements: '木木水',
    basicMeaning: '此名字五行属性为木，寓意生机勃勃，充满活力，有成长和发展的潜力。',
    nameScore: 85
  };
  
  // 模拟详细分析数据
  const mockDetailAnalysis = {
    characterAnalysis: '性格开朗，富有创造力，善于表达，具有领导才能，但有时过于理想化。',
    destinyAnalysis: '命运较为顺遂，中年之前有贵人相助，事业发展顺利，晚年安康。',
    careerAnalysis: '适合从事创意、管理、教育、文化等领域工作，事业上容易获得成功。',
    wealthAnalysis: '财运中上，中年后财富积累明显，但需注意投资风险。',
    relationshipAnalysis: '人际关系和谐，易得长辈赏识，婚姻较为稳定，子女孝顺。',
    healthAnalysis: '体质较好，但需注意肝脏和神经系统保养，保持良好作息习惯。',
    suggestions: '此名整体较为吉利，建议保持积极心态，注重自身修养，事业上可多尝试创新。'
  };
  
  const displayBasicData = analysisData?.basicAnalysis || (name ? mockBasicAnalysis : null);
  const displayDetailData = analysisData?.detailAnalysis || (showPayment ? null : mockDetailAnalysis);
  
  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-3xl mx-auto bg-white rounded-xl shadow-md overflow-hidden">
        <div className="p-6">
          <h2 className="text-2xl font-bold text-gray-900 text-center mb-6">姓名测算</h2>
          
          {/* 姓名输入表单 */}
          <form onSubmit={handleSubmit} className="mb-8">
            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
              <div>
                <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
                  姓名
                </label>
                <input
                  type="text"
                  id="name"
                  className="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="请输入姓名"
                  required
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  性别
                </label>
                <div className="flex space-x-4 mt-2">
                  <div className="flex items-center">
                    <input
                      id="male"
                      name="gender"
                      type="radio"
                      checked={gender === 1}
                      onChange={() => setGender(1)}
                      className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                    />
                    <label htmlFor="male" className="ml-2 block text-sm text-gray-700">
                      男
                    </label>
                  </div>
                  <div className="flex items-center">
                    <input
                      id="female"
                      name="gender"
                      type="radio"
                      checked={gender === 2}
                      onChange={() => setGender(2)}
                      className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                    />
                    <label htmlFor="female" className="ml-2 block text-sm text-gray-700">
                      女
                    </label>
                  </div>
                </div>
              </div>
            </div>
            
            {error && (
              <div className="text-red-500 text-sm text-center mt-4">
                {error}
              </div>
            )}
            
            <div className="mt-6">
              <button
                type="submit"
                disabled={loading}
                className={`w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${loading ? 'opacity-70 cursor-not-allowed' : ''}`}
              >
                {loading ? '分析中...' : '开始测算'}
              </button>
            </div>
          </form>
          
          {/* 分析结果 */}
          {displayBasicData && (
            <div>
              {/* 基础分析 */}
              <div className="bg-indigo-50 p-4 rounded-lg mb-6">
                <h3 className="text-lg font-medium text-indigo-900 mb-4">基础分析</h3>
                
                <div className="grid grid-cols-2 gap-4 mb-4">
                  <div>
                    <span className="text-gray-500">姓名：</span>
                    <span className="font-medium">{displayBasicData.name}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">性别：</span>
                    <span className="font-medium">{displayBasicData.gender}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">笔画：</span>
                    <span className="font-medium">{displayBasicData.strokes}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">五行：</span>
                    <span className="font-medium">{displayBasicData.fiveElements}</span>
                  </div>
                </div>
                
                <div className="mb-4">
                  <span className="text-gray-500">基础寓意：</span>
                  <p className="text-gray-700 mt-1">{displayBasicData.basicMeaning}</p>
                </div>
                
                <div className="flex items-center justify-between">
                  <span className="text-gray-500">综合评分：</span>
                  <div className="flex items-center">
                    <span className="text-2xl font-bold text-indigo-600">{displayBasicData.nameScore}</span>
                    <span className="text-gray-500 ml-1">/100</span>
                  </div>
                </div>
              </div>
              
              {/* 付费内容 */}
              {showPayment ? (
                <div className="bg-indigo-50 p-6 rounded-lg border border-indigo-100 text-center">
                  <h3 className="text-lg font-medium text-indigo-900 mb-2">查看详细分析</h3>
                  <p className="text-indigo-700 mb-4">
                    详细分析包含性格、命运、事业、财富、人际关系等全面解读
                  </p>
                  <button
                    onClick={handlePayment}
                    disabled={paymentLoading}
                    className={`inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${paymentLoading ? 'opacity-70 cursor-not-allowed' : ''}`}
                  >
                    {paymentLoading ? '处理中...' : `支付${isAuthenticated ? '0.1' : '1.1'}元查看详情`}
                  </button>
                  <p className="mt-2 text-xs text-indigo-500">
                    {isAuthenticated ? '已登录用户优惠价' : '登录后可享受优惠价格'}，VIP会员无限查看
                  </p>
                </div>
              ) : displayDetailData && (
                <div className="mb-6">
                  <h3 className="text-lg font-medium text-gray-900 mb-4">详细分析</h3>
                  <div className="space-y-4">
                    <div>
                      <h4 className="text-md font-medium text-gray-800">性格分析</h4>
                      <p className="text-gray-700">{displayDetailData.characterAnalysis}</p>
                    </div>
                    
                    <div>
                      <h4 className="text-md font-medium text-gray-800">命运分析</h4>
                      <p className="text-gray-700">{displayDetailData.destinyAnalysis}</p>
                    </div>
                    
                    <div>
                      <h4 className="text-md font-medium text-gray-800">事业分析</h4>
                      <p className="text-gray-700">{displayDetailData.careerAnalysis}</p>
                    </div>
                    
                    <div>
                      <h4 className="text-md font-medium text-gray-800">财富分析</h4>
                      <p className="text-gray-700">{displayDetailData.wealthAnalysis}</p>
                    </div>
                    
                    <div>
                      <h4 className="text-md font-medium text-gray-800">人际关系</h4>
                      <p className="text-gray-700">{displayDetailData.relationshipAnalysis}</p>
                    </div>
                    
                    <div>
                      <h4 className="text-md font-medium text-gray-800">健康分析</h4>
                      <p className="text-gray-700">{displayDetailData.healthAnalysis}</p>
                    </div>
                    
                    <div className="bg-yellow-50 p-4 rounded-lg">
                      <h4 className="text-md font-medium text-yellow-800">综合建议</h4>
                      <p className="text-gray-700">{displayDetailData.suggestions}</p>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}
          
          {/* 操作按钮 */}
          <div className="mt-8 flex justify-center">
            <button
              onClick={() => navigate('/tools')}
              className="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              返回工具列表
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default NameAnalysis;
